package com.ruoyi.web.controller.bid;

import com.ruoyi.common.constant.MessageConstant;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.oss.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 通用接口
 */
@Api(tags = "通用接口")
@RequestMapping("/bid/template")
@RestController
@Slf4j
public class TBidCommonController {

    /**
     * 注入阿里云 OSS 文件上传工具类
     */
    @Autowired
    private AliOssUtil aliOssUtil ;

    @PostMapping("/upload")
    @ApiOperation("文件上传接口")
    public AjaxResult upload(MultipartFile file) {
        log.info("文件上传：{}" , file);
        try {
            //获取原始文件的文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件文件名的后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //生成新文件名
            String objectName = UUID.randomUUID() + extension ;
            //上传文件并获取图片 url
            String url = aliOssUtil.upload(file.getBytes(), objectName);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", originalFilename);
            ajax.put("newFileName", FileUtils.getName(originalFilename));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (IOException e) {
            log.info("文件上传失败...{}" , e) ;
            return AjaxResult.error(MessageConstant.UPLOAD_FAILED) ;
        }
    }

}
